require( '$d/css/common.less' );
require( './style.less' );
define( [
	'jquery',
	'require',
	'header',
	'message',
	'api',
	'bigwe_utils',
	'selector'
], function( $, require ) {
	var thisApi = require( 'api' ).GATHER;
	var bu = require( 'bigwe_utils' );
	var msg = require( 'message' );


	var textLib = {
		'1': '审核通过',
		'-1': '审核未通过',
		'0': '待审核'
	};

	$.get( thisApi.GET_ACCOUNT_BYID, {
		id: bu.getUrlParam( 'id' )
	}, function( data ) {
		data = typeof data === 'string' ? $.parseJSON( data ) : data;
		if ( data.ret === 0 ) {
			var tempFull = data.data;
			$( '#fm_account [name]' ).each( function() {
				$( this ).val( tempFull[ $( this ).attr( 'name' ) ] );
			} )

			$( '#fm_account [name="status"]' ).val( textLib[ tempFull[ 'status' ] ] || '' );
			$( 'select' ).selectpicker( 'refresh' );
		}
	} );

	$( document ).on( 'submit', '#fm_account', function() {

		var platform = $( '[name="platform"]', this ).val();
		var name = $.trim( $( '[name="account_name"]', this ).val() );
		var history_link = $.trim( $( '[name="history_link"]', this ).val() );


		if ( name === '' ) {
			msg.showWarning( '请输入待采集的平台的账号名称', msg.showTime );
			return false;
		}

		try {
			var url = new URL( history_link );
			if ( url.host.indexOf( platform ) < 0 ) {
				msg.showWarning( '您输入的地址和当前平台不匹配', msg.showTime );
				return false;
			}
		} catch ( e ) {
			msg.showWarning( '请输入一个正确的url', msg.showTime );
			return false;
		}

		// 提交
		$( '[type="submit"]', this ).prop( 'disabled', 'disabled' );
		$.post( thisApi.ADD_ACCOUNT, $( this ).serialize(), function( data ) {
			data = typeof data === 'string' ? $.parseJSON( data ) : data;
			if ( data.ret === 0 ) {
				msg.show( '保存成功！', msg.showTime );
				setTimeout( function() {
					location.href = $( '#goback' ).attr( 'href' );
				}, 2e3 );
			} else {
				msg.showWarning( data.msg, msg.showTime );
			}
		} ).always( function() {
			$( '[type="submit"]', this ).removeAttr( 'disabled' );
		}.bind( this ) );

		return false;
	} );
} );